package page_lib

import (
	"errors"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"math"
)

type PageParam struct {
	Total       float64    `json:"total"`        //总条数
	PerPage     float64    `json:"per_page"`     //每页显示条数
	CurrentPage int        `json:"current_page"` //当前页数
	LastPage    float64    `json:"last_page"`    //最后一页数
	Data        g.ArrayAny `json:"data"`         //具体数
}

func GetPage(model *gdb.Model, currentPage int, perPage int) (*PageParam, error) {
	pageParam := &PageParam{}
	if perPage <= 0 {
		return pageParam, errors.New("per_page不能为0")
	}
	totalCount, _ := model.Count()

	pageParam.Total = gconv.Float64(totalCount)
	pageParam.PerPage = gconv.Float64(perPage)
	pageParam.CurrentPage = currentPage
	pageParam.LastPage = math.Ceil(gconv.Float64(totalCount) / gconv.Float64(perPage))

	data, _ := model.Page(currentPage, perPage).All()
	pageParam.Data = gconv.Interfaces(data)

	return pageParam, nil
}
